package com.zjsystem.zjsy.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zjsystem.zjsy.dto.ChatMessages;
import com.zjsystem.zjsy.result.Result;
import com.zjsystem.zjsy.service.ChatMessagesService;
import com.zjsystem.zjsy.utils.UUIDUtils;
import com.zjsystem.zjsy.websocket.WebSocketServer;
import org.junit.platform.commons.util.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.yaml.snakeyaml.events.Event;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 调控记录 前端控制器
 * </p>
 *
 * @author wyf
 * @since 2024-07-17
 */
@RestController
@RequestMapping("/zjsy/chatMessages")
public class ChatMessagesController {

    @Resource
    private ChatMessagesService messagesService;


    @GetMapping("/")
    public String index() {
        return "index"; // 返回index.html
    }

    @RequestMapping(value = "/favicon.ico")
    @ResponseStatus(value = HttpStatus.NO_CONTENT)
    public void favicon() {
        // No operation. Just to avoid 404 error for favicon.ico
    }

    @GetMapping("/sendMsg")
    public Result sendMsg(@RequestParam("msgId") String sessionId) {
        // sessionId代表会话的唯一Id 如果为空代表是一个新会话 如果不为空代表是与某人的聊天记录
        // 所以返回给前端的格式 应该根据sessionId分组返回
        ChatMessages messages = new ChatMessages();
        messages.setSenderId("wyf123");
        messages.setSessionId("MSG" + UUIDUtils.random());
        if (StringUtils.isNotBlank(sessionId)) {
            messages.setSessionId(sessionId);
        }
        messages.setSenderName("王云飞");
        messages.setSenderUnit("后端组");
        messages.setReceiverId("zs123");
        messages.setReceiverName("张三");
        messages.setReceiverUnit("后端组");
        messages.setMessageText("hello zhangsan");
        messages.setSendType("未回复");
        messages.setSendTime(new Date());
        messagesService.save(messages);
        WebSocketServer.sendInfo("2", JSON.toJSONString(messages));
        return Result.ok();
    }

    @GetMapping("/getMsg")
    public Result getMsg() {
        List<ChatMessages> messagesList = messagesService.list();
        Map<String, List<ChatMessages>> stringListMap = messagesList.stream().collect(Collectors.groupingBy(ChatMessages::getSessionId));
        return Result.ok(stringListMap);
    }

}

